
/*! Ruotong Account Embed - License & Invoice Modules (vanilla JS) */
(function (global){
  const STORE = {
    tracks: "ruotong_tracks",
    invoices: "ruotong_invoices",
    balance: "ruotong_balance",
    coins: "ruotong_coins"
  };

  function fmt(num){ return Number(num||0).toLocaleString("zh-CN"); }
  function notify(root, msg){
    let t = root.querySelector(".rtacc-toast");
    if(!t){
      t = document.createElement("div");
      t.className = "rtacc-toast";
      root.appendChild(t);
    }
    t.textContent = msg;
    t.classList.add("show");
    clearTimeout(t._timer);
    t._timer = setTimeout(()=> t.classList.remove("show"), 1600);
  }

  // ========= License Module =========
  function LicenseModule(root, opts){
    this.root = typeof root === "string" ? document.querySelector(root) : root;
    this.opts = opts || {};
    this.state = { tracks: [] };
    this.filter = "all"; // all/active/inactive
    this.init();
  }
  LicenseModule.prototype.load = async function(){
    if (typeof this.opts.fetchTracks === "function"){
      this.state.tracks = await this.opts.fetchTracks();
    }else if (Array.isArray(this.opts.tracks)){
      this.state.tracks = this.opts.tracks;
    }else{
      // fallback mock
      this.state.tracks = JSON.parse(localStorage.getItem(STORE.tracks) || "[]");
      if(this.state.tracks.length === 0){
        this.state.tracks = [
          {
            id:"63k1e58d-u600-3buf-1r4h-kmgv9cb4r5q5",
            title:"コミカル上昇音_ポワン",
            artist:"癒しの音スタジオ–SoundTeam",
            uploader:"癒しの音スタジオ–SoundTeam",
            code:"63k1e58d-u600-3buf-1r4h-kmgv9cb4r5q5",
            usage:"个人用途（非商用）",
            scope:"个人账户",
            region:"中国",
            duration:"随片永久",
            activated:true,
            activation:{contact:"王小明",phone:"13800000000",owner:"王小明",purpose:"个人使用",project:"短视频《周一快乐》",channels:"抖音、快手",activatedAt:"2025-06-09 11:07:42"}
          },
          {
            id:"v0wg7k8e-1swb-gmzu-02ct-n9tvutgy69w7",
            title:"张力 #01", artist:"MATSU", uploader:"MATSU",
            code:"v0wg7k8e-1swb-gmzu-02ct-n9tvutgy69w7",
            usage:"连续剧/综艺", scope:"网络", region:"中国", duration:"随片永久",
            activated:false
          }
        ];
        localStorage.setItem(STORE.tracks, JSON.stringify(this.state.tracks));
      }
    }
  };
  LicenseModule.prototype.saveState = function(){
    // 仅本地演示：将 tracks 写回 localStorage。生产对接用 opts.onSaveActivate 或后端接口。
    localStorage.setItem(STORE.tracks, JSON.stringify(this.state.tracks));
  };
  LicenseModule.prototype.init = async function(){
    if(!this.root) return;
    this.root.classList.add("rtacc");
    this.root.innerHTML = [
      '<div class="rtacc-panel">',
      ' <div class="rtacc-toolbar">',
      '   <div class="rtacc-filter">',
      '     <button class="rtacc-filter-btn active" data-filter="all">全部音频</button>',
      '     <button class="rtacc-filter-btn" data-filter="active">已授权音频</button>',
      '     <button class="rtacc-filter-btn" data-filter="inactive">未授权音频</button>',
      '   </div>',
      '   <div class="rtacc-search"><input type="search" placeholder="搜索标题 / 作者 / 授权代码…"></div>',
      ' </div>',
      ' <div class="rtacc-list"></div>',
      '</div>',
      // modal
      '<div class="rtacc-modal" id="rtacc-activate">',
      ' <div class="rtacc-card">',
      '  <div class="rtacc-mhead"><h3>激活音乐授权</h3><button class="rtacc-close">×</button></div>',
      '  <form class="rtacc-form" id="rtacc-activate-form">',
      '   <div><div class="rtacc-label">联系人 *</div><input class="rtacc-input" name="contact" required></div>',
      '   <div><div class="rtacc-label">手机号 *</div><input class="rtacc-input" name="phone" required></div>',
      '   <div class="full"><div class="rtacc-label">选择用途</div>',
      '     <label style="display:inline-flex;align-items:center;gap:6px;margin-right:14px"><input type="radio" name="purpose" value="公司使用" checked><span>公司使用</span></label>',
      '     <label style="display:inline-flex;align-items:center;gap:6px"><input type="radio" name="purpose" value="个人使用"><span>个人使用</span></label>',
      '   </div>',
      '   <div class="full"><div class="rtacc-label">被授权者（填写音频使用者真实姓名） *</div><input class="rtacc-input" name="owner" required></div>',
      '   <div><div class="rtacc-label">项目名称 *</div><input class="rtacc-input" name="project" required></div>',
      '   <div><div class="rtacc-label">投放渠道 *</div><input class="rtacc-input" name="channels" required></div>',
      '   <div class="rtacc-mactions full">',
      '     <button type="button" class="rtacc-btn" data-close>取消</button>',
      '     <button class="rtacc-btn primary" type="submit">提交并生成授权书</button>',
      '   </div>',
      '  </form>',
      '  <div class="rtacc-hint">授权项目信息填写不清晰，可能导致授权书无效。请根据项目实际情况如实且详尽地填写授权信息，以保证您的合法权益。</div>',
      ' </div>',
      '</div>'
    ].join("");

    await this.load();
    this.render();

    const r = this.root;
    r.addEventListener("click",(e)=>{
      if(e.target.matches(".rtacc-filter-btn")){
        r.querySelectorAll(".rtacc-filter-btn").forEach(x=>x.classList.remove("active"));
        e.target.classList.add("active");
        this.filter = e.target.dataset.filter;
        this.render();
      }
      if(e.target.matches(".rtacc-more")){
        const det = e.target.closest(".rtacc-item").nextElementSibling;
        const open = det.classList.toggle("open");
        e.target.textContent = open ? "收起授权信息 ⌃" : "查看授权信息 ⌄";
      }
      if(e.target.matches(".rtacc-close,[data-close]")){
        r.querySelector("#rtacc-activate").classList.remove("open");
      }
    });
    document.addEventListener('keydown', function(ev){
      if(ev.key==='Escape'){ const m = document.querySelector('#rtacc-invoice-modal.open'); if(m) m.classList.remove('open'); }
    });

    
    r.addEventListener('change', (e)=>{
      if(e.target && e.target.name==='cnType'){
        const form = r.querySelector('#rtacc-invoice-form');
        const isSpecial = e.target.value==='增值税专用发票';
        ['cnAddress','cnPhone','cnBank','cnAccount'].forEach(n=>{
          const el = form.querySelector('[name='+n+']');
          if(!el) return;
          if(isSpecial){ el.setAttribute('required',''); }
          else{ el.removeAttribute('required'); }
          // Visually hint: add or remove asterisk
        });
      }
    });
r.addEventListener("input",(e)=>{
      if(e.target.closest(".rtacc-search")) this.render();
    });
    r.querySelector("#rtacc-activate-form").addEventListener("submit", this.submitActivate.bind(this));
  };
  LicenseModule.prototype.render = function(){
    const listEl = this.root.querySelector(".rtacc-list");
    listEl.innerHTML = "";
    const kw = (this.root.querySelector(".rtacc-search input").value || "").toLowerCase().trim();
    const tracks = this.state.tracks.filter(t=>{
      if(this.filter==="active" && !t.activated) return false;
      if(this.filter==="inactive" && t.activated) return false;
      if(kw && !(t.title.toLowerCase().includes(kw) || (t.artist||"").toLowerCase().includes(kw) || (t.code||"").toLowerCase().includes(kw))) return false;
      return true;
    });

    if(tracks.length === 0){
      listEl.innerHTML = '<div style="padding:28px;text-align:center;color:#6b7280">暂无记录</div>';
      return;
    }

    for(const t of tracks){
      const row = document.createElement("div");
      row.className = "rtacc-item";
      const cover = `<div class="rtacc-cover" style="background:linear-gradient(135deg,#111 0,#333 100%)"></div>`;
      const title = [
        '<div class="rtacc-title">',
        `  <div>${t.title}</div>`,
        t.activated ? '<span class="rtacc-badge success">已激活</span>' : '<span class="rtacc-badge warn">未激活</span>',
        `  <span class="rtacc-muted">by ${t.artist||""}</span>`,
        '</div>'
      ].join("");
      const kv = [
        '<div class="rtacc-kv">',
        ` <div><span>授权代码：</span>${t.code||"—"}</div>`,
        ` <div><span>购买用途：</span>${t.usage||"—"}</div>`,
        ` <div><span>授权范围：</span>${t.scope||"—"}</div>`,
        ` <div><span>授权地域：</span>${t.region||"—"}</div>`,
        ` <div><span>授权期限：</span>${t.duration||"—"}</div>`,
        '</div>',
        `<div class="rtacc-more" data-id="${t.id}">查看授权信息 ⌄</div>`
      ].join("");
      const meta = `<div class="rtacc-meta">${title}${kv}</div>`;
      const btnDownload = `<button class="rtacc-btn" data-dl="${t.id}">下载音乐</button>`;
      const btnCert = `<button class="rtacc-btn primary" data-cert="${t.id}">${t.activated? "查看授权书":"生成授权书"}</button>`;
      const actions = `<div class="rtacc-actions">${btnDownload}${btnCert}</div>`;
      row.innerHTML = cover + meta + actions;
      listEl.appendChild(row);

      // details
      const details = document.createElement("div");
      details.className = "rtacc-details";
      details.innerHTML = [
        '<div class="rtacc-dgrid">',
        `<div><span>音频名：</span>${t.title}</div>`,
        `<div><span>音频人：</span>${t.artist||"—"}</div>`,
        `<div><span>版权所属：</span>${t.uploader||"—"}</div>`,
        `<div><span>用途：</span>${t.usage||"—"}</div>`,
        `<div><span>地域：</span>${t.region||"—"}</div>`,
        `<div><span>期限：</span>${t.duration||"—"}</div>`,
        t.activated ? [
          `<div><span>被授权者：</span>${t.activation.owner||"—"}</div>`,
          `<div><span>项目名称：</span>${t.activation.project||"—"}</div>`,
          `<div><span>投放渠道：</span>${t.activation.channels||"—"}</div>`,
          `<div><span>激活时间：</span>${t.activation.activatedAt||"—"}</div>`
        ].join("") : ""
        ,'</div>'
      ].join("");
      listEl.appendChild(details);
    }

    // buttons
    listEl.querySelectorAll("[data-dl]").forEach(btn=>{
      btn.addEventListener("click", ()=>{
        if(typeof this.opts.onDownload === "function") this.opts.onDownload(btn.dataset.dl);
        notify(this.root,"模拟下载：已开始下载音乐");
      });
    });
    listEl.querySelectorAll("[data-cert]").forEach(btn=>{
      btn.addEventListener("click", ()=>{
        const t = this.state.tracks.find(x=>x.id===btn.dataset.cert);
        if(!t.activated){
          this.openActivate(t.id);
        }else{
          window.open((this.opts.certificateUrl||"certificate.html")+"?songId="+encodeURIComponent(t.id),"_blank");
        }
      });
    });
  };
  LicenseModule.prototype.openActivate = function(id){
    this.activeId = id;
    const m = this.root.querySelector("#rtacc-activate");
    m.classList.add("open");
        // default region CN
        const regionBtn = m.querySelector('[data-region="CN"]'); if(regionBtn){ regionBtn.click(); }
        const typeSel = m.querySelector('[name=cnType]'); if(typeSel){ typeSel.value=''; }
    m.querySelector("form").reset();
  };
  LicenseModule.prototype.submitActivate = async function(e){
    e.preventDefault();
    const fd = new FormData(e.target);
    const payload = Object.fromEntries(fd.entries());
    if(!payload.contact || !payload.phone || !payload.owner || !payload.project || !payload.channels){
      notify(this.root,"请完善必填项"); return;
    }
    const t = this.state.tracks.find(x=>x.id===this.activeId);
    const activation = {
      contact: payload.contact, phone: payload.phone, purpose: payload.purpose || "公司使用",
      owner: payload.owner, project: payload.project, channels: payload.channels,
      activatedAt: new Date().toISOString().slice(0,19).replace('T',' ')
    };
    if(typeof this.opts.onActivate === "function"){
      try{
        const res = await this.opts.onActivate(t.id, activation);
        // 可根据 res 写回更多字段
      }catch(err){ console.error(err); notify(this.root,"激活失败，请稍后再试"); return; }
    }
    t.activated = true; t.activation = activation;
    this.saveState();
    this.root.querySelector("#rtacc-activate").classList.remove("open");
    this.render();
    notify(this.root,"激活成功，已生成授权信息");
    setTimeout(()=> window.open((this.opts.certificateUrl||"certificate.html")+"?songId="+encodeURIComponent(t.id),"_blank"), 300);
  };

  // ========= Invoice Module =========
  function InvoiceModule(root, opts){
    this.root = typeof root === "string" ? document.querySelector(root) : root;
    this.opts = opts || {};
    this.state = { payments: [], invoices: {}, balance: 0, coins: 0 };
    this.init();
  }
  InvoiceModule.prototype.load = async function(){
    if(typeof this.opts.fetchPayments === "function"){
      this.state.payments = await this.opts.fetchPayments();
    }else if(Array.isArray(this.opts.payments)){
      this.state.payments = this.opts.payments;
    }else{
      this.state.payments = [
        {id:"202509301029360001", amount:5000, method:"微信", paidAt:"2025-09-30 10:30:09", status:"已入账"},
        {id:"20250603101060001", amount:5000, method:"微信", paidAt:"2025-06-03 10:10:44", status:"已入账"},
        {id:"202505191918360001", amount:2000, method:"微信", paidAt:"2025-05-19 19:19:36", status:"已入账"}
      ];
    }
    if(typeof this.opts.fetchBalances === "function"){
      const b = await this.opts.fetchBalances();
      this.state.balance = b.balance||0; this.state.coins = b.coins||0;
    }else{
      this.state.balance = Number(localStorage.getItem(STORE.balance) || 3606.2);
      this.state.coins = Number(localStorage.getItem(STORE.coins) || 21921);
    }
    this.state.invoices = JSON.parse(localStorage.getItem(STORE.invoices) || "{}");
  };
  InvoiceModule.prototype.saveInvoices = function(map){
    localStorage.setItem(STORE.invoices, JSON.stringify(map));
  };
  InvoiceModule.prototype.init = async function(){
    if(!this.root) return;
    this.root.classList.add("rtacc");
    this.root.innerHTML = [
      '<div class="rtacc-panel">',
      '  <div class="rtacc-sum">',
      '    <div class="rtacc-stat"><h4>充值余额（元）</h4><div class="n" id="rtacc-balance">-</div></div>',
      '    <div class="rtacc-stat"><h4>V币（个）</h4><div class="n" id="rtacc-coins">-</div></div>',
      '  </div>',
      '  <div style="padding:8px 18px 14px">',
      '    <table class="rtacc-table"><thead><tr><th>订单编号</th><th>充值金额</th><th>支付方式</th><th>支付时间</th><th>发票状态</th><th>操作</th></tr></thead>',
      '    <tbody id="rtacc-inv-tbody"></tbody></table>',
      '  </div>',
      '</div>',
      // modal
      '<div class="rtacc-modal" id="rtacc-invoice-modal">',
      ' <div class="rtacc-card">',
      '  <div class="rtacc-mhead"><h3>申请发票</h3><button class="rtacc-close">×</button></div>',
      
      '  <form class="rtacc-form" id="rtacc-invoice-form">'
      '    <input type="hidden" name="paymentId">'
      '    <div class="full"><div class="rtacc-label">开票主体</div>'
      '      <div class="rtacc-filter" role="tablist" aria-label="开票主体">'
      '        <button type="button" class="rtacc-filter-btn active" data-region="CN">中国大陆公司</button>'
      '        <button type="button" class="rtacc-filter-btn" data-region="INTL">海外公司 / Foreign company</button>'
      '      </div></div>'
      '    <div><div class="rtacc-label">发票金额（元）</div><input class="rtacc-input" name="amount" readonly></div>'
      '    <div><div class="rtacc-label">接收邮箱 *</div><input class="rtacc-input" type="email" name="email" required></div>'
      '    <div class="full" data-region-panel="CN">'
      '      <div class="rtacc-label">中国大陆公司信息</div>'
      '    </div>'
      '    <div data-region-panel="CN"><div class="rtacc-label">发票类型 *</div><select class="rtacc-input" name="cnType" required><option value="">请选择</option><option value="电子普通发票">增值税电子普通发票</option><option value="增值税专用发票">增值税专用发票</option></select></div>'
      '    <div data-region-panel="CN"><div class="rtacc-label">发票抬头（公司全称） *</div><input class="rtacc-input" name="cnTitle" placeholder="与营业执照一致" required></div>'
      '    <div data-region-panel="CN"><div class="rtacc-label">统一社会信用代码 *</div><input class="rtacc-input" name="cnTaxNo" placeholder="18位统一社会信用代码" required></div>'
      '    <div data-region-panel="CN"><div class="rtacc-label">单位地址 <span class="rtacc-muted">（专用发票必填）</span></div><input class="rtacc-input" name="cnAddress" placeholder="营业执照注册地址"></div>'
      '    <div data-region-panel="CN"><div class="rtacc-label">单位电话 <span class="rtacc-muted">（专用发票必填）</span></div><input class="rtacc-input" name="cnPhone" placeholder="座机或常用电话"></div>'
      '    <div data-region-panel="CN"><div class="rtacc-label">开户行 <span class="rtacc-muted">（专用发票必填）</span></div><input class="rtacc-input" name="cnBank" placeholder="xx银行xx支行"></div>'
      '    <div data-region-panel="CN"><div class="rtacc-label">银行账号 <span class="rtacc-muted">（专用发票必填）</span></div><input class="rtacc-input" name="cnAccount" placeholder="仅限公司账号"></div>'
      '    <div class="full" data-region-panel="INTL" hidden>'
      '      <div class="rtacc-label">Foreign company information</div>'
      '    </div>'
      '    <div data-region-panel="INTL" hidden><div class="rtacc-label">Company name *</div><input class="rtacc-input" name="intlCompany" required></div>'
      '    <div data-region-panel="INTL" hidden><div class="rtacc-label">Country/Region *</div><input class="rtacc-input" name="intlCountry" required></div>'
      '    <div data-region-panel="INTL" hidden><div class="rtacc-label">VAT/Tax ID</div><input class="rtacc-input" name="intlTaxId" placeholder="optional"></div>'
      '    <div data-region-panel="INTL" hidden><div class="rtacc-label">Registered address *</div><input class="rtacc-input" name="intlAddress" required></div>'
      '    <div class="full"><div class="rtacc-label">发票内容</div><select class="rtacc-input" name="content"><option value="信息技术服务费">信息技术服务费</option><option value="服务费">服务费</option></select></div>'
      '    <div class="full"><div class="rtacc-label">备注</div><textarea class="rtacc-textarea" name="note" placeholder="可填写项目信息 / 开票要求等"></textarea></div>'
      '    <div class="rtacc-mactions full"><button type="button" class="rtacc-btn" data-close>取消</button><button class="rtacc-btn primary" type="submit">提交申请</button></div>'
      '  </form>',
      ' </div>',
      '</div>'
    ].join("");

    await this.load();
    this.render();

    const r = this.root;
    r.addEventListener("click",(e)=>{
      if(e.target.matches(".rtacc-close,[data-close]")) r.querySelector("#rtacc-invoice-modal").classList.remove("open");
      if(e.target.classList.contains('rtacc-modal')) r.querySelector('#rtacc-invoice-modal').classList.remove('open');
      if(e.target.matches("[data-apply]")){
        const pid = e.target.dataset.apply;
        const p = this.state.payments.find(x=>x.id===pid);
        const m = r.querySelector("#rtacc-invoice-modal");
        m.classList.add("open");
        // default region CN
        const regionBtn = m.querySelector('[data-region="CN"]'); if(regionBtn){ regionBtn.click(); }
        const typeSel = m.querySelector('[name=cnType]'); if(typeSel){ typeSel.value=''; }
        m.querySelector("[name=paymentId]").value = p.id;
        m.querySelector("[name=amount]").value = p.amount;
      }
      if(e.target.matches("[data-view]")){
        const pid = e.target.dataset.view;
        window.open((this.opts.invoiceUrl||"invoice.html")+"?paymentId="+encodeURIComponent(pid),"_blank");
      }
    });
    r.querySelector("#rtacc-invoice-form").addEventListener("submit", this.submitInvoice.bind(this));
  };
  InvoiceModule.prototype.render = function(){
    const r = this.root;
    r.querySelector("#rtacc-balance").textContent = Number(this.state.balance).toLocaleString("zh-CN",{minimumFractionDigits:1,maximumFractionDigits:1});
    r.querySelector("#rtacc-coins").textContent = Number(this.state.coins).toLocaleString("zh-CN");
    const body = r.querySelector("#rtacc-inv-tbody");
    body.innerHTML = "";
    const map = this.state.invoices;

    for(const p of this.state.payments){
      const tr = document.createElement("tr");
      const applied = map[p.id];
      tr.innerHTML = [
        `<td>${p.id}</td>`,
        `<td>¥${fmt(p.amount)}</td>`,
        `<td>${p.method||"—"}</td>`,
        `<td>${p.paidAt||"—"}</td>`,
        `<td>${applied ? (applied.status || "已申请") : "未申请"}</td>`,
        `<td>${applied ? `<button class="rtacc-btn" data-view="${p.id}">查看发票</button>` : `<button class="rtacc-btn primary" data-apply="${p.id}">申请发票</button>`}</td>`
      ].join("");
      body.appendChild(tr);
    }
  };
  
InvoiceModule.prototype.submitInvoice = async function(e){
    e.preventDefault();
    const fd = new FormData(e.target);
    const p = Object.fromEntries(fd.entries());
    // Normalize - default headType to 公司 for compatibility
    if(!p.headType){ p.headType = '公司'; }
    const region = p.region || 'CN';
    // Basic checks
    if(!p.email || !p.amount){
      notify(this.root,'请完善必填项'); return;
    }
    if(region==='CN'){
      if(!p.cnType || !p.cnTitle || !p.cnTaxNo){
        notify(this.root,'请填写中国大陆公司必填项'); return;
      }
      // 专用发票需要更多字段
      if(p.cnType==='增值税专用发票'){
        for(const k of ['cnAddress','cnPhone','cnBank','cnAccount']){
          if(!p[k]){ notify(this.root,'专用发票需填写：单位地址、电话、开户行、账号'); return; }
        }
      }
      p.title = p.cnTitle; p.taxNo = p.cnTaxNo; p.invoiceType = p.cnType; p.region='CN';
    }else{ // INTL
      if(!p.intlCompany || !p.intlCountry || !p.intlAddress){
        notify(this.root,'Please fill in required fields for foreign company'); return;
      }
      p.title = p.intlCompany; p.invoiceType = 'Commercial invoice'; p.region='INTL';
      p.taxNo = p.intlTaxId||''; p.country = p.intlCountry; p.address = p.intlAddress;
    }
    // 后端对接：opts.onInvoiceApply(paymentId, payload)
    if(typeof this.opts.onInvoiceApply === 'function'){
      try{ await this.opts.onInvoiceApply(p.paymentId, p); }catch(err){ console.error(err); notify(this.root,'提交失败，请稍后再试'); return; }
    }
    const map = this.state.invoices;
    map[p.paymentId] = { ...p, status:'已申请', appliedAt: new Date().toISOString().slice(0,19).replace('T',' ') };
    this.saveInvoices(map);
    this.state.invoices = map;
    this.root.querySelector('#rtacc-invoice-modal').classList.remove('open');
    this.render();
    notify(this.root,'发票申请已提交');
    setTimeout(()=> window.open((this.opts.invoiceUrl||'invoice.html')+'?paymentId='+encodeURIComponent(p.paymentId),'_blank'), 300);
  };


  // ========= Public API =========
  const RTAccount = {
    initLicense: (selector, options) => new LicenseModule(selector, options),
    initInvoice: (selector, options) => new InvoiceModule(selector, options)
  };
  global.RTAccount = RTAccount;
})(window);
